// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import {
    NotificationCenter
} from "../utils/NotificationCenter";

import {
    S2CProtocol,
    C2S_LOGIN,
    S2C_LOGIN,
    C2S_QQ_LOGIN as C2S_WX_LOGIN,
    C2S_UPDATE_WX_INFO,
    L2EProtocol
} from "./ELProtocol";

import {
    readStorage,
    gameVersion,
    loginUrl,
    commonPost,
    updateWxInfoUrl,
    getQrCodetUrl,
    commonGet,
    noticeUrl
    // cryptKey
} from "../utils/CommonUtils";

// import Crypt = require("../utils/Crypt.js");

const {ccclass, property} = cc._decorator;

@ccclass
export default class LoginProto extends cc.Component {

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        NotificationCenter.Instance.on("requestQQLogin", this.requestMiniWxLogin, this);
        NotificationCenter.Instance.on("requestLogin", this.requestLogin, this);
        // NotificationCenter.Instance.on("requestUpdateWxInfo", this.requestUpdateWxInfo, this);
        NotificationCenter.Instance.on("loginHandle", this.loginHandle, this);
        // NotificationCenter.Instance.on("requestQRCode", this.requestQRCode, this);
        // NotificationCenter.Instance.on("qrCodeHandler", this.qrCodeHandler, this);
        NotificationCenter.Instance.on("requestNotice", this.requestNotice, this);
        NotificationCenter.Instance.on("handleNotice", this.handleNotice, this);
    }
    
    onDestroy() {
        NotificationCenter.Instance.off("requestQQLogin", this.requestMiniWxLogin, this);
        NotificationCenter.Instance.off("requestLogin", this.requestLogin, this);
        // NotificationCenter.Instance.off("requestUpdateWxInfo", this.requestUpdateWxInfo, this);
        NotificationCenter.Instance.off("loginHandle", this.loginHandle, this);
        // NotificationCenter.Instance.off("qrCodeHandler", this.qrCodeHandler, this);
        // NotificationCenter.Instance.off("requestQRCode", this.requestQRCode, this);
        NotificationCenter.Instance.off("requestNotice", this.requestNotice, this);
        NotificationCenter.Instance.off("handleNotice", this.handleNotice, this);
    }
    
    start () {

    }

    // update (dt) {}

    private requestMiniWxLogin() {
        // session_key 未过期，并且在本生命周期一直有效
        // result中包含encryptedData和iv
        let code = readStorage('login_code');
        let encrypte = readStorage('login_encrypte');
        let iv = readStorage('login_iv');
        // 将res.code、result.encryptedData、result.iv发送到服务器
        // 发起网络请求
        // wx.request({
        //     url: 'https://test.com/onLogin',
        //     data: {
        //         code: code,
        //         encryptedData: encrypte,
        //         iv: iv,
        //     }
        // });
        let loginData = <C2S_WX_LOGIN>{};
        // loginData.wxcode = code;
        console.log('.........................:'+code);
        let tokenStr:string = readStorage("token") || "";
        if (tokenStr == null || tokenStr == undefined || tokenStr == "undefined") {
            tokenStr = "";
        }

        cc.log("device：" + cc.sys.os);
        cc.log("token:"+tokenStr);
        cc.log("wxcode:"+code);
        loginData.device = cc.sys.os;
        loginData.token = tokenStr;
        loginData.game_version = gameVersion;
        let wxOpt = window['wx'].getLaunchOptionsSync();
        console.log(wxOpt);
        // loginData.package_info = "0_1_0#0_0";
        let promoterCode = '';
        if (Object.keys(wxOpt.query).length == 0) {
            promoterCode = '0#0';
        }else {
            if (wxOpt.query.myPromoterCode != null) {
                promoterCode = wxOpt.query.myPromoterCode;
                promoterCode = promoterCode.replace('_','#');
            }else{
                promoterCode = '0#0';
            }
        }
        // if (Object.keys(wxOpt.query).length == 0){
        //     promoterCode = '0#0';
        // }else{
        //     promoterCode = String(wxOpt.query).replace('_','#');
        // }
        loginData.package_info = "0_wx_"+promoterCode+"_0";
        // loginData.encryptedData = encrypte;
        // loginData.iv = iv;
        commonPost(loginUrl, "loginHandle", loginData);
    }

    private requestNativeWxLogin() {
        let loginData = <C2S_LOGIN>{};
        let code = readStorage('login_code') || "";
        let tokenStr:string = readStorage("token") || "";
        if (tokenStr == null || tokenStr == undefined || tokenStr == "undefined") {
            tokenStr = "";
        }
        if (code == null || code == undefined || code == "undefined") {
            code = "";
        }

        cc.log("device：" + cc.sys.os);
        cc.log("token:"+tokenStr);
        loginData.device = cc.sys.os;
        loginData.token = tokenStr;
        loginData.game_version = gameVersion;
        loginData.package_info = "0_wx_0#0_0";
        loginData.wxcode = code;

    }

    private requestLogin() {
        let loginData = <C2S_LOGIN>{};
        let tokenStr:string = readStorage("token") || "";
        if (tokenStr == null || tokenStr == undefined || tokenStr == "undefined") {
            tokenStr = "";
        }

        cc.log("device：" + cc.sys.os);
        cc.log("token:"+tokenStr);
        loginData.device = cc.sys.os;
        loginData.token = tokenStr;
        loginData.game_version = gameVersion;
        loginData.package_info = "0_1_0#0_0";
        // loginData.wxcode = "";
        
        commonPost(loginUrl, "loginHandle", loginData);
    }

    private loginHandle(response:string) {
        let resp = JSON.parse(response);
        if (this.handleError(resp) == true) {
            cc.warn("通用错误处理");

            NotificationCenter.Instance.emit(L2EProtocol.l2e_login_error, resp.msg);
            return;
        }

        let responseData = resp.data;

        let updateData: S2C_LOGIN = <S2C_LOGIN>{};
        updateData.token = responseData.token;
        updateData.myPromoterCode = responseData.myPromoterCode;

        updateData.playerId = responseData.playerId;
        updateData.nickName = responseData.nickName;
        updateData.headIcon = responseData.headIcon;

        updateData.rmb = responseData.rmb;
        updateData.trmb = responseData.trmb;
        updateData.bl = responseData.bl;
        updateData.minTRmbExchange = responseData.minTRmbExchange;

        updateData.adNum = responseData.adNum;
        updateData.sharedNum = responseData.sharedNum;
        updateData.getRMBNum = responseData.getRMBNum;

        updateData.loginServerTime = resp.serverTime;

        updateData.adGuideCode = responseData.adGuideCode;
        updateData.tfAdNum = responseData.tfAdNum;

        // cc.log("收到登录回复:"+responseData.nickName);
        NotificationCenter.Instance.emit(S2CProtocol.s2c_login, updateData);
    }

    // private requestUpdateWxInfo() {
    //     let data = <C2S_UPDATE_WX_INFO>{};
    //     let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
    //     let user = logicCenter.getUserInfo();
    //     data.token = user.token;
    //     data.nickName = user.nickName;
    //     data.headIcon = user.headIcon;
    //     if(user.nickName == null || user.nickName.length == 0) {
    //         return;
    //     }
    //     // if (user.headIcon == null || user.headIcon.length <= 11) {
    //     //     return;
    //     // }
    //     commonPost(updateWxInfoUrl, "UpdateWxInfoHandle", data);
    // }

    private handleError(response: any) {
        if (response.code != 200) {
            console.log("服务器错误提示："+response.msg);
            return true;
        }

        return false;
    }

    // private requestQRCode() {
    //     let logicCenter = cc.find('LogicCenterNode').getComponent('LogicCenter');
    //     let user = logicCenter.getUserInfo();
    //     commonPost(getQrCodetUrl, "qrCodeHandler", {token: user.token});
    // }

    // private qrCodeHandler(response: string) {
    //     let resp = JSON.parse(response);
    //     if (this.handleError(resp) == true) {
    //         cc.warn("通用错误处理");
    //         return;
    //     }

    //     // saveStorage('qrcode', resp.data.imgStr);
    // }

    private requestNotice() {
        commonGet(noticeUrl, 'handleNotice');
    }

    private handleNotice(response: string) {
        cc.log("handleNotice:"+response);
    }
}
